import { Button, Form, Input, message, Modal, Tabs } from 'antd';
import { FormInstance, useForm } from 'antd/lib/form/Form';
import React, { useEffect, useRef, useState } from 'react';
import { getVCodeByPhone, loginUser, registerUser, TTarget, resetPasswordByPhone } from '../../api/threeApi';
import ChangePw from './ChangePw';

let loginCodeTimer: any = null;
let registerCodeTimer: any = null;

export default function Login(props: { visable: boolean; onChange: (visable: boolean) => void }) {
	const [visable, setVisable] = useState(false || props.visable);
	const [formLogin] = useForm();
	const [formRegister] = useForm();
	const [isVCodeLogin, setIsVCodeLogin] = useState(false);
	const [loginCodeTime, _setLoginCodeTime] = useState(60);
	const loginCodeTimeRef = useRef(loginCodeTime);
	const setLoginCodeTime = (data: number): void => {
		loginCodeTimeRef.current = data;
		_setLoginCodeTime(data);
	};

	const [registerCodeTime, _setRegisterCodeTime] = useState(60);
	const registerCodeTimeRef = useRef(registerCodeTime);
	const setRegisterCodeTime = (data: number): void => {
		registerCodeTimeRef.current = data;
		_setRegisterCodeTime(data);
	};

	const [formReset] = useForm();
	const [visableChangePw, setVisableChangePw] = useState(false);

	useEffect(() => {
		setVisable(props.visable);
	}, [props.visable]);

	const handleGetVCode = (form: FormInstance, target: TTarget) => {
		form.validateFields(['phone']).then((values) => {
			if (target === 'login') {
				loginCodeTimer = setInterval(() => {
					setLoginCodeTime(loginCodeTimeRef.current - 1);
					if (loginCodeTimeRef.current === 0) {
						clearInterval(loginCodeTimer);
						setLoginCodeTime(60);
					}
				}, 1000);
			} else if (target === 'register') {
				registerCodeTimer = setInterval(() => {
					setLoginCodeTime(registerCodeTimeRef.current - 1);
					if (registerCodeTimeRef.current === 0) {
						clearInterval(registerCodeTimer);
						setRegisterCodeTime(60);
					}
				}, 1000);
			}
			getVCodeByPhone(values.phone, target).then((res) => {
				console.log(res);
			});
		});
	};
	return (
		<div>
			<Modal
				bodyStyle={{ padding: 0 }}
				style={{ borderRadius: 10, overflow: 'hidden', paddingBottom: 0 }}
				width={444}
				visible={visable}
				onOk={() => {}}
				onCancel={() => {
					setVisable(false);
					props.onChange(false);
				}}
				footer={null}
			>
				<img src={require('../../image/login.png').default} alt="" />
				<div className="plr50 pb80 login">
					<Tabs
						defaultActiveKey="1"
						centered={true}
						onChange={() => {
							// form.resetFields();
						}}
					>
						<Tabs.TabPane tab="登录" key="1">
							<Form
								form={formLogin}
								name="basic"
								initialValues={{ remember: true }}
								onFinish={() => {
									formLogin.validateFields().then((values) => {
										loginUser(values)
											.then((res) => {
												message.success('登录成功');
												setVisable(false);
												props.onChange(false);
												window.location.reload();
											})
											.catch((err) => {
												message.success('登录失败');
											});
									});
								}}
								onFinishFailed={() => {}}
							>
								{isVCodeLogin ? (
									<>
										<Form.Item
											name="phone"
											rules={[{ required: true, message: '请输入手机号' }]}
											style={{ width: '100%' }}
										>
											<Input placeholder="手机号" />
										</Form.Item>

										<div className="d-f jc-b">
											<Form.Item
												name="vcode"
												rules={[{ required: true, message: '请输入验证码' }]}
												style={{ width: '100%' }}
											>
												<Input placeholder="输入验证码" />
											</Form.Item>
											<Form.Item className="ml8">
												<Button
													block
													type="primary"
													onClick={() => handleGetVCode(formLogin, 'login')}
													disabled={loginCodeTimeRef.current < 60}
													style={{ width: 112 }}
												>
													{loginCodeTimeRef.current < 60
														? loginCodeTimeRef.current
														: '获取验证码'}
												</Button>
											</Form.Item>
										</div>
									</>
								) : (
									<>
										<Form.Item
											name="phone"
											rules={[{ required: true, message: '请输入手机号/用户名/邮箱' }]}
										>
											<Input placeholder="手机号/用户名/邮箱" />
										</Form.Item>

										<Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
											<Input.Password placeholder="密码" />
										</Form.Item>
									</>
								)}

								<Button block type="primary" htmlType="submit">
									登录
								</Button>
								<div className="d-f jc-b c-hint-b mt8">
									{isVCodeLogin ? (
										<span
											className="cp"
											onClick={() => {
												formLogin.resetFields();
												setIsVCodeLogin(false);
											}}
										>
											密码登录
										</span>
									) : (
										<span
											className="cp"
											onClick={() => {
												formLogin.resetFields();
												setIsVCodeLogin(true);
											}}
										>
											手机验证码登录
										</span>
									)}

									<span
										className="cp"
										onClick={() => {
											setVisableChangePw(true);
											setVisable(false);
											props.onChange(false);
										}}
									>
										忘记密码？
									</span>
								</div>
							</Form>
						</Tabs.TabPane>
						<Tabs.TabPane tab="注册" key="2">
							<Form
								form={formRegister}
								name="basic"
								initialValues={{ remember: true }}
								onFinish={() => {
									formRegister.validateFields().then((values) => {
										registerUser(values)
											.then((res) => {
												message.success('注册成功');
												setVisable(false);
												props.onChange(false);
											})
											.catch((err) => {
												message.success('注册失败');
											});
									});
								}}
								onFinishFailed={() => {}}
								// wrapperCol={{ span: 24 }}
							>
								<Form.Item
									name="phone"
									rules={[{ required: true, message: '请输入手机号/用户名/邮箱' }]}
									style={{ width: '100%' }}
								>
									<Input placeholder="手机号/用户名/邮箱" />
								</Form.Item>

								<div className="d-f jc-b">
									<Form.Item
										name="vcode"
										rules={[{ required: true, message: '请输入验证码' }]}
										style={{ width: '100%' }}
									>
										<Input placeholder="输入验证码" />
									</Form.Item>
									<Form.Item className="ml8">
										<Button
											block
											type="primary"
											onClick={() => handleGetVCode(formRegister, 'register')}
											disabled={registerCodeTimeRef.current < 60}
										>
											{registerCodeTimeRef.current < 60
												? registerCodeTimeRef.current
												: '获取验证码'}
										</Button>
									</Form.Item>
								</div>
								<Form.Item name="password" rules={[{ required: true, message: '请设置密码' }]}>
									<Input.Password placeholder="请设置密码（6-20位）" />
								</Form.Item>

								<Button block type="primary" htmlType="submit">
									确认注册
								</Button>
							</Form>
						</Tabs.TabPane>
					</Tabs>
				</div>
			</Modal>

			<Modal
				bodyStyle={{ padding: 0 }}
				style={{ borderRadius: 10, overflow: 'hidden', paddingBottom: 0 }}
				width={578}
				visible={visableChangePw}
				onOk={() => {}}
				onCancel={() => {
					setVisableChangePw(false);
				}}
				footer={null}
			>
				<Form
					form={formReset}
					name="basic"
					onFinish={() => {
						formReset.validateFields().then((values) => {
							console.log(values);
							resetPasswordByPhone(values)
								.then((res) => {
									console.log(res);
									message.success('修改成功，请重新登录');
									setVisableChangePw(false);
								})
								.catch((err) => {
									message.error(err.data.msg);
								});
						});
					}}
					onFinishFailed={() => {}}
				>
					<ChangePw form={formReset} />
				</Form>
			</Modal>
		</div>
	);
}
